$(function () {

    //监听iframe 变化 进行参数传递
    /* window.frames["contentFrame"].onload(function() {
         debugger;
         if (vm.loadParams.data){
             window.frames["mainFrame"][vm.loadParams.vueName].loadData(vm.loadParams);
             vm.loadParams = null;
         }
     });*/

    $(document).on("mouseenter", "#navbar-collapse ul.nav li.actives", function () {
        $(this).addClass("active");
        $(this).addClass("active");
        var lists = $(this).attr("id");
        $("div." + lists).show();
        $(this).siblings().find(".menu_pos").hide();
        $(this).siblings().removeClass("active");
    });
    $(document).on("mouseleave", "#navbar-collapse ul.nav li.actives", function () {
        var lists = $(this).attr("id");
        $("div." + lists).hide();
        $(this).removeClass("active");
    });


    /*(function longPolling(webCount) {
        $.ajax({
            url: "/message/message/getMessage",
            data: {"webCount": webCount},
            dataType: "text",
            timeout: 180000,// 请求响应时间 3分钟
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log("请求失败:" + errorThrown);
                if (textStatus == "timeout") { // 请求超时
                    longPolling(0); // 递归调用
                    // 其他错误，如网络错误等 不再递归调用
                } else {
                    //longPolling(0);
                }
            },
            success: function (data, textStatus) {
                // console.log("请求成功:" +data);
                if (textStatus == "success") { // 请求成功
                    vm.message = JSON.parse(data);
                    longPolling(vm.message.count);
                }
            }
        });
    })();*/
});

//生成菜单
var menuItem = Vue.extend({
    name: 'menu-item',
    props: {item: {}, index: 0},
    computed: {
        idIndex: function () {
            return 'active' + this.index;
        },
        classIndex: function () {
            return 'menu_pos active' + this.index;
        },
        //动态计算样式
        styleObject: function () {
            var width = 120 * this.item.list.length + 2 + "px";
            var cListLength = 1;
            if (this.item.list) {
                this.item.list.forEach(function (element) { //循环取出最大长度
                    if (element.list) {
                        if (element.list.length > cListLength) {
                            cListLength = element.list.length;
                        }
                    }
                });

                this.item.list.forEach(function (element) { //循环变更最大长度
                    if (element.list) {
                        var num = cListLength - element.list.length;
                        for (var i = 0; i < num; i++) {
                            element.list.push({})
                        }
                    }
                });
            }
            var height = 30 * cListLength + 30 + "px";
            return {width: width, height: height};

        }
    },
    template: [
        '<li class="actives" :id="idIndex">',
        '<div :class="classIndex">',
        '<div  class="nav_contain" :style="styleObject" >',
        '	<ul v-if="item.type === 0"  class="menu">',
        '		<li class="nav_type" :type="item.type"  v-for="(itemC, indexC) in item.list"  >',
        '			<span style="font-size: 13px">{{itemC.name}}</span>' +
        '			<ul v-if="itemC.type === 0" class="lists" >',
        '				<li    v-for="itemCC in itemC.list" >',
        /*'					<i v-if="itemCC.icon != null" :class="itemCC.icon"></i>',*/
        '					<a style="font-size: 10px"  href="javascript:void(0)" @click="menuClick(itemCC)">{{itemCC.name}}</a>  ',
        '				</li>												',
        '			</ul>	',
        '			<ul v-if="itemC.type === 1" class="lists" >',
        '				<li>',
        /*'					<i v-if="itemCC.icon != null" :class="itemCC.icon"></i>',*/
        '					<a style="font-size: 10px" href="javascript:void(0)" @click="menuClick(itemC)">{{itemC.name}}</a>  ',
        '				</li>												',
        '			</ul>	',
        '		</li>',
        '	</ul>',
        '</div>',
        '</div>',
        '<a class="menu" href="#"><i v-if="item.icon != null" :class="item.icon"></i>{{item.name}}</a>',
        '</li>'

        /*  '<li >',
          '	<a v-if="item.type === 0" href="javascript:;" data-toggle="dropdown">',
          '		<i v-if="item.icon != null" :class="item.icon"></i>',
          '		<span>{{item.name}}</span>',
          '	</a>',
          '	<ul v-if="item.type === 0" class="dropdown-menu" role="menu">',
          '		<menu-item :item="item" v-for="item in item.list"></menu-item>',
          '	</ul>',

          '	<a v-if="item.type === 1 && item.parentId === 0" :href="\'#\'+item.url">',
          '		<i v-if="item.icon != null" :class="item.icon"></i>',
          '		<span>{{item.name}}</span>',
          '	</a>',

          '	<a v-if="item.type === 1 && item.parentId != 0" :href="\'#\'+item.url">' +
          '		<i v-if="item.icon != null" :class="item.icon"></i>' +
          '		<i v-else class="fa fa-circle-o"></i> {{item.name}}</a>',
          '</li>'*/
    ].join(''),
    methods:{
        menuClick : function (item) {
            this.$emit('zy-menu-click', item);
        }
    },
});

//iframe自适应
$(window).on('resize', function () {
    var $content = $('.content');
    $content.height($(this).height() - 120);
    $content.find('iframe').each(function () {
        $(this).height($content.height());
    });
}).resize();

//注册菜单组件
Vue.component('menuItem', menuItem);


var vm = new Vue({
    el: '#rrapp',
    data: {
        user: {},
        message: {},
        menuList: {},
        main: "main.html",
        password: '',
        newPassword: '',
        navTitle: "首页",
        navMenu: "",
        navIcon: "fa fa-home",
        loadParams: {data:null,hash:null,vueName: 'vm'},
        menuTabList: [],
        menuTab: null,
        tabIndex:0,
        currentVm: null, //默认vm
        dataParams:{},//传输参数
        guide: null,// 系统引导页配置
    },

    computed:{
        messageEnum : function () {
            return this.message.serviceTypeEnum;
        }
    },
    watch:{
        guide:{
            handler(val){
                //异步更新当前用户的引导状态
                if (JSON.stringify(val) !== vm.user.guide){
                    $.ajax({
                        type: "POST",
                        url: "sys/user/updateGuide",
                        data: JSON.stringify(val),
                        contentType: "application/json",
                        success: function (result) {
                            if (result.code != 0) {
                                alert("异步更新引导页错误," +result.msg);
                            }
                        }
                    });
                }

            },
            deep:true ////深度监听，可监听到对象、数组的变化
        }
    },
    methods: {
        getMenuList: function (event) {
            $.getJSON("sys/menu/nav?_" + $.now(), function (r) {
                // console.log(r.menuList);
                vm.menuList = r.menuList;
            });
        },
        getUser: function () {
            $.getJSON("sys/user/info?_" + $.now(), function (r) {
                vm.user = r.user;
                if (r.user.guide){
                    vm.guide = JSON.parse(r.user.guide);
                }
                if(vm.user.sellerId>20){
                    vm.menuTab = 'main.html';
                    vm.menuTabList =   [{
                        title: '主页',
                        url: 'main.html'
                    }];
                }else {
                    vm.menuTab='modules/order/erporder.html';
                    vm.menuTabList =   [{
                        title: '订单列表',
                        url: 'modules/order/erporder.html'
                    }]
                }
                //debugger;
            });
        },
        updatePassword: function () {
            layer.open({
                type: 1,
                skin: 'layui-layer-lan',
                title: "修改密码",
                area: ['550px', '270px'],
                shadeClose: false,
                content: jQuery("#passwordLayer"),
                btn: ['修改', '取消'],
                btn1: function (index) {
                    var data = "password=" + vm.password + "&newPassword=" + vm.newPassword;
                    $.ajax({
                        type: "POST",
                        url: "sys/user/password",
                        data: data,
                        dataType: "json",
                        success: function (result) {
                            if (result.code == 0) {
                                layer.close(index);
                                layer.alert('修改成功', function (index) {
                                    location.reload();
                                });
                            } else {
                                layer.alert(result.msg);
                            }
                        }
                    });
                }
            });
        },
        donate: function () {
            layer.open({
                type: 2,
                title: false,
                area: ['806px', '467px'],
                closeBtn: 1,
                shadeClose: false,
                content: ['http://cdn.renren.io/donate.jpg', 'no']
            });
        },
        //页面跳转
        goto: function (data) {
            window.location.hash = data.hash;
            if (data.data){
                vm.loadParams.data = data.data;
            }
            if (data.vueName){
                vm.loadParams.vueName = data.vueName;
            }
        },
        //查看全部消息
        lookAll: function () {
            window.location.hash = "modules/message/message.html";
        },
        //标记已读
        markupRead: function () {
            var ids= [];
            $.each(vm.message.items,function(index,value){
                ids.push(value.id);
            });
            $.ajax({
                type: "POST",
                url: "message/message/markupRead",
                data: JSON.stringify(ids),
                contentType: "application/json",
                success: function (result) {
                    if (result.code == 0) {
                        layer.alert('修改成功', function (index) {
                            location.reload();
                        });
                    } else {
                        layer.alert(result.msg);
                    }
                }
            });
        },
        removeMenuTab: function (targetName) {
            var tabs = this.menuTabList;
            var activeName = this.menuTab;
            if (activeName === targetName) {
                tabs.forEach(function(tab, index) {
                    if (tab.url === targetName) {
                        var nextTab = tabs[index + 1] || tabs[index - 1];
                        if (nextTab) {
                            activeName = nextTab.url;
                        }
                    }
                });
            }

            this.menuTab = activeName;
            this.menuTabList = tabs.filter(function (tap) {
                return tap.url !== targetName;
            });
        },
        addMenuTab: function(menuData) {
            // 判断当前菜单是否已经打开
            var activeName = null;
            this.menuTabList.forEach(function(tab, index) {
                if (tab.url === menuData.url) {
                    activeName = menuData.url;
                }
            });
            if (activeName){
                this.menuTab = activeName;
                this.loadFrame({target:{name:activeName}});
                return;
            }
            // 添加新菜单
            var newTabName = menuData.url;
            this.menuTabList.push({
                title: menuData.name,
                url: menuData.url,
            });
            this.menuTab = newTabName;
        },
        zyMenuClick: function (item) {
            //打开新页面
            this.addMenuTab(item);
        },
        /**
         * url: 连接
         * name: 名称
         * blank: false 打开新tab
         * closeBlank: false 关闭原tab 仅在blank 为true 生效
         * params:{}传递参数
         * @param data
         */
        zyRouter: function (data) {
            // 传数据参数
            if (data.vmName){
                this.currentVm = data.vmName;
            }
            if (data.params){
                this.dataParams = data.params;
            }
            if (data.blank && data.blank === true){// 打开新tab页
                if(data.closeBlank && data.closeBlank === true){
                    this.removeMenuTab(this.menuTab);
                }
                this.addMenuTab(data);
            }else {
                // 替换当前页内容
                this.menuTabList.forEach(function(tab, index)  {
                    if (tab.url === this.menuTab) {
                        tab.url = data.url;
                    }
                });
                this.menuTab = data.url;
            }

            /*if(data.vmName && data.params){
                debugger;
                $("#"+data.vmName).load(function() {
                    debugger;
                    window.frames[data.url][data.vmName].loadData(data.params);
                });
            }*/

        },

        loadFrame: function (data) {
            if (vm.currentVm ){
                window.frames[data.target.name][vm.currentVm].loadData(vm.dataParams);
                // 传递参数之后 重置参数
                vm.currentVm = null;
                vm.dataParams = null;
            }
        },
    },
    created: function () {
        this.getMenuList();
        this.getUser();
    },
  /*  updated: function () {
        //路由
        /!*var router = new Router();
        routerList(router, vm.menuList);
        router.start();*!/
    },*/

});

/*function loadFrame(obj){
    if (vm.currentVm ){
        window.frames[obj.name][vm.currentVm].loadData(vm.dataParams);
        // 传递参数之后 重置参数
        vm.currentVm = null;
        vm.dataParams = null;
    }
}*/

function routerList(router, menuList) {
    for (var key in menuList) {
        var menu = menuList[key];
        if (menu.type == 0) {
            routerList(router, menu.list);
        } else if (menu.type == 1) {
            router.add('#' + menu.url, function () {
                var url = window.location.hash;

                //替换iframe的url
                vm.main = url.replace('#', '');
                vm.navTitle = $("a[href='" + url + "']").text();
                vm.navMenu = $("a[href='" + url + "']").parents("li.actives").find('a.menu').text();
                vm.navIcon = $("a[href='" + url + "']").parents("li.actives").find('a.menu i').attr("class");
                //导航菜单展开
                /*$(".dropdown-menu li").removeClass("active");
                $("a[href='" + url + "']").parents("li").addClass("active");
                vm.navTitle = $("a[href='" + url + "']").text();
                vm.navMenu = $(".my-menu").find("li.active").children("a")[0].text;*/
            });
        }
    }
}
